package com.sergio.compress.utils;

import org.springframework.data.mongodb.core.mapping.Document;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @Author : Sergio.D
 * @Description :
 * @CreateDate ：2023/6/15 17:20
 */
public class CommonUtil {

    //设置collectionName
    public static void setCollectionName(Class<?> clazz, String collectionName) {
        try {
            Field collectionField = clazz.getDeclaredField("collection"); // 获取collection属性
            collectionField.setAccessible(true); // 设置为可访问
            Document document = collectionField.getAnnotation(Document.class); // 获取@Document注解对象
            if (document != null) {
                InvocationHandler handler = Proxy.getInvocationHandler(document);
                Field memberValuesField = handler.getClass().getDeclaredField("memberValues"); // 获取注解对象的成员变量map
                memberValuesField.setAccessible(true); // 设置为可访问
                Map<String, Object> memberValues = (Map<String, Object>) memberValuesField.get(handler);
                memberValues.put("collection", collectionName); // 将collection属性设置为新值
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final Random random = new Random();

    //生成随机字符串
    public static String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(CHARACTERS.length());
            char randomChar = CHARACTERS.charAt(randomIndex);
            sb.append(randomChar);
        }
        return sb.toString();
    }

    public static byte[] serializeList(List<?> list) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(list);
            oos.close();
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    public static byte[] generateRandomBytes(int length) {
        byte[] bytes = new byte[length];
        random.nextBytes(bytes);
        return bytes;
    }

}
